// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------
// Modification history:
// feature: provide query interfaces
// feature: discovery support client and server
// ------------------------------------------------------------------

#include <discovery/participant/timedevent/DSClientEvent.h>

#include <elog/Log.hpp>

#include <edds/rtps/builtin/BuiltinProtocols.h>
#include <edds/rtps/builtin/data/ParticipantProxyData.h>
#include <discovery/endpoint/EDPClient.h>
#include <discovery/participant/PDPClient.h>
#include <rtps/participant/RTPSParticipantImpl.h>
#include <edds/rtps/resources/ResourceEvent.h>
#include <deps/common/shared_mutex.hpp>

namespace evbs {
namespace ertps {
namespace rtps {

DSClientEvent::DSClientEvent(PDPClient* p_PDP, double interval)
    : TimedEvent(
          p_PDP->getRTPSParticipant()->getEventResource(), [this]() { return event(); }, interval),
      mp_PDP(p_PDP),
      mp_EDP(static_cast<EDPClient*>(mp_PDP->getEDP())),
      client_sync_interval_(interval) {}

DSClientEvent::~DSClientEvent() {}

bool DSClientEvent::event() {
    // logDebug(CLIENT_PDP_THREAD, "Client " << mp_PDP->getRTPSParticipant()->getGuid() << " DSClientEvent Period");
    bool restart = false;

    if (getIntervalMilliSec() == PDP_RESTART_TIMER_DELAY) {
        update_interval_millisec(client_sync_interval_);
        cancel_timer();
        restart_timer();
    }

    if (mp_PDP->connected_servers().size() < mp_PDP->remote_server_locators().size()) {
        // If there are pending servers, we need to run the event again
        restart = true;
    }

    // If we are still not connected to all servers, we need to keep pinging the unmatched ones
    if (restart) {
        // This marks to announceParticipantState that the announcement is only meant for missing servers,
        // so it is not a periodic announcement
        mp_PDP->_serverPing = true;
        WriteParams __wp = WriteParams::WRITE_PARAM_DEFAULT;
        mp_PDP->announceParticipantState(false, false, __wp);
        logDebug(CLIENT_PDP_THREAD, "Client " << mp_PDP->getRTPSParticipant()->getGuid() << " PDP announcement");
    }

    return restart;
}

}  // namespace rtps
}  // namespace ertps
} /* namespace evbs */
